package equappcontrollers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"smartcap-api/models"
	"path"
	"time"
)


//文件相关接口
type FileUploadController struct {
	beego.Controller
}


//上传文件到服务器
//func (c *FileController) Fileupload() {
//	fmt.Println("上传文件到服务器")
//	c.Ctx.WriteString("test successful")
//}


//上传下载文件的页面
func (c * FileUploadController) Get() {
	c.TplName = "upload.html"
}


//上传文件
func (this *FileUploadController) Fileupload() {
	FileLogs.Info("====上传文件====")
	file, information, err := this.GetFile("file")  //返回文件，文件信息头，错误信息
	filetype := this.GetString("filetype")
	deviceid := this.GetString("deviceid")
	coordinate := this.GetString("coordinate")

	//查询该设备所属公司
	var labelrows []models.LabelInfo
	o := orm.NewOrm()
	if _, err := o.Raw("SELECT * FROM label_info  where labelid = ?",deviceid ).QueryRows(&labelrows); err != nil{
		fmt.Println("err")
		return
	}
	var company = ""
	for _,labelrow := range labelrows{
		company = labelrow.Unit
		break
	}

	if err != nil {
		this.Ctx.WriteString("File retrieval failure")
		return
	}
	defer file.Close()    //关闭上传的文件，否则出现临时文件不清除的情况  mmp错了好多次啊

	timeUnix:=time.Now().Unix()
	timeStr:=time.Now().Format("2006-01-02 15:04:05")

	filename := information.Filename           //将文件信息头的信息赋值给filename变量
	err = this.SaveToFile("file", path.Join("static/upload",filename))  //保存文件的路径。保存在static/upload中   （文件名）
	Filedata := models.FileInfo{Filename:filename,Filetype:filetype,Filepath:"static/upload",Deviceid:deviceid,Company:company,Coordinate:coordinate,Timestamp:timeUnix,Uploadtime:timeStr}
	_,err1:= models.AddFile(&Filedata)

	type JSONS struct {
		//必须的大写开头
		Error_code int
	}

	if (err != nil)&&(err1 != nil) {
		data := &JSONS{1,}
		this.Data["json"] = data
		this.ServeJSON()
	} else {
		data := &JSONS{0}
		this.Data["json"] = data
		this.ServeJSON()
	}
	//this.TplName = "upload.html"             //停留在当前界面
}








